<?php
class Place_MerchantPlaceController extends Zend_Controller_Action{
    
    public function init(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        $userSession = new Zend_Session_Namespace('user_session');
        $userSession->setExpirationSeconds($constants->SESSION_TIMEOUT);
        $user = $userSession->user;
        $userId = $user->sale_user_id;
        try{
            if(isset($userId)){
                // $userRoleModel = new Admin_Model_SaleUserRole();
                // $userRole = $userRoleModel->getRoleOfUser($userId);
//                 
                // $saleUserRoleFeature = new Admin_Model_SaleUserRoleFeature();
                // $featureArr = $saleUserRoleFeature->getFeatureOfUserRole($userRole);
                // $featureIdArr = array();
                // foreach ($featureArr as $key => $value) {
                    // array_push($featureIdArr,$value->sale_feature_id);
                // }
                // if(!in_array($constants->FEATURE_APPROVE_DEAL, $featureIdArr)){
                    // $this->_redirect('/admin/index');
                // }
                $this->view->title = "Approve Deal";    
                $this->view->userName = $user->full_name;
                
            }else{
                $this->_redirect('/place/index/index');
            }   
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function indexAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession->user;
            $userId = $user->sale_user_id;
            
            $APPROVED = $constants->APPROVED;
            $approve = $APPROVED;
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $merchantNumber = intval($merchantPlaceModel->getPlaceNumberByStatus($approve));
            
            $userRoleModel = new Place_Model_SaleUserRole();
            $userRole = $userRoleModel->getRoleOfUser($userId);
            
            $saleUserRoleFeature = new Place_Model_SaleUserRoleFeature();
            $featureArr = $saleUserRoleFeature->getFeatureOfUserRole($userRole);
            $featureIdArr = array();
            foreach ($featureArr as $key => $value) {
                array_push($featureIdArr,$value->sale_feature_id);
            }
            if(!in_array($constants->FEATURE_CHECK_PLACE, $featureIdArr)){
                $this->_redirect('/place/index/index');
            }
            
            $adminCategoryModel = new Place_Model_AdminCategory();
            $allCategory = $adminCategoryModel->getAllCategory();
            
            $this -> view -> userFeature = $featureArr;
            $this->view->merchantNumber = $merchantNumber;
            $this->view->title = "Search Place";
            $this->view->placeCategory = $allCategory;
            
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function deletePlaceAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        
        try{
            $normalUtils = new My_Utils_NormalUtils();
            $DB = $normalUtils->getNormalDb(1);
            
            if (isset($_GET['placeList'])) {
                $placeList = $_GET['placeList'];
                $place_id_str_list = explode(",", $placeList);
                $places_id_list = implode(",", array_map("intval", $place_id_str_list));
                $deleteQuery = "UPDATE merchant_place SET `status` = 10 WHERE place_id IN ($places_id_list)";
                $DB -> query($deleteQuery);
                echo $registry -> constants -> DELETE_MERCHANT_SUCCESS;
            } else {
                echo $registry -> constants -> ERROR_STRING;
            }
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function requestPlaceAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        
        try{
            
            $normalUtils = new My_Utils_NormalUtils();
            $DB = $normalUtils->getNormalDb(1);
            
            $APPROVE_REQUEST = $constants -> APPROVE_REQUEST;
            if (isset($_GET['placeList'])) {
                $placeList = $_GET['placeList'];
                $place_id_str_list = explode(",", $placeList);
                $places_id_list = implode(",", array_map("intval", $place_id_str_list));
                $deleteQuery = "UPDATE merchant_place SET status = $APPROVE_REQUEST " . " WHERE place_id IN ($places_id_list) ";
                $DB -> query($deleteQuery);
                echo $registry -> constants -> APPROVE_MERCHANT_SUCCESS;
            } else {
                echo $registry -> constants -> ERROR_STRING;
            }
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
        
    }
    
    public function addPlaceAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        $normalUtils = new My_Utils_NormalUtils();
        $DB = $normalUtils->getNormalDb(1);
        
        $DB -> beginTransaction();
        
        try{
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession -> user;
            $userId = $user -> sale_user_id;
    
            $SUCCESS_STRING = $constants -> SUCCESS_STRING;
            $APPROVE_NOT = $constants -> APPROVE_NOT;
            
            if(!isset($_POST['name']) || !isset($_POST['address']) || 
               !isset($_POST['map_icon'])){
                throw new Exception($constants->MISSING_PARAMETER);
            }
            
            $name = $_POST['name'];
            $address = $_POST['address'];
            $phone = $_POST['phone'];
            $mail = $_POST['mail'];
            $website = $_POST['website'];
            
            $description = $_POST['description'];
            $productService = $_POST['product_service'];
            $tag = $_POST['tag'];
            
            $categoryId = $_POST['category_id'];
            $mapIcon = $_POST['map_icon'];
            $smallPicture = str_replace('.png', '_thum.png', $mapIcon);
            $provinceId = $_POST['province'];
            
            $latitude = $_POST['latitude'];
            $longitude = $_POST['longitude'];
            
            $arrParams = array("name"=>$name,
                                "address"=>$address,
                                "phone" => $phone, 
                                "mail" => $mail, 
                                "website" => $website, 
                                "product_service" => $productService, 
                                "description" => $description, 
                                "working_time" => $constants->PLACE_WORKING_TIME, 
                                "longitude" => $longitude, 
                                "latitude" => $latitude, 
                                "tag" => $tag, 
                                "carparking_number" => $constants->PLACE_CARPARKING_NUMBER, 
                                "grade" => $constants -> PLACE_GRADE, 
                                "small_picture" => $smallPicture, 
                                "province_id" => $provinceId, 
                                "version" => $constants -> PLACE_VERSION, 
                                "search_priority" => $constants->PLACE_SEARCH_PRIORITY,
                                "actived" => $constants->PLACE_ACTIVED,
                                "no_of_comment" => $constants->PLACE_NO_OF_COMMENT,
                                "map_icon" => $mapIcon,
                                "working_date" => $constants->PLACE_WORKING_DATE,
                                "sale_user_id" => $userId,
                                "status" => $constants->APPROVE_NOT,
                                "altitude" => $constants->PLACE_ALTITUDE,
                                "edit_status" =>$constants->PLACE_EDIT_STATUS,
                                "category_id" => $categoryId
                                );
            
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $merchantPlaceModel->save($arrParams);
            
            $DB -> commit();
            echo $constants -> ADD_MERCHANT_SUCCESS;
        }catch(Exception $e){
            $DB -> rollback();
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }

    public function updateMerchantPlaceAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        $normalUtils = new My_Utils_NormalUtils();
        $DB = $normalUtils->getNormalDb(1);
        
        $DB -> beginTransaction();
        
        try{
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession -> user;
            $userId = $user -> sale_user_id;
    
            $SUCCESS_STRING = $constants -> SUCCESS_STRING;
            $APPROVE_NOT = $constants -> APPROVE_NOT;
            
            if(!isset($_POST['name']) || !isset($_POST['address']) ||
                !isset($_POST['place_id']) || !isset($_POST['map_icon'])){
                throw new Exception($constants->MISSING_PARAMETER);
            }
            
            $placeId = $_POST['place_id'];
            $name = $_POST['name'];
            $address = $_POST['address'];
            $phone = $_POST['phone'];
            $mail = $_POST['mail'];
            $website = $_POST['website'];
            
            $description = $_POST['description'];
            $productService = $_POST['product_service'];
            $tag = $_POST['tag'];
            
            $categoryId = $_POST['category_id'];
            $mapIcon = $_POST['map_icon'];
            $smallPicture = str_replace('.png', '_thum.png', $mapIcon);
            $provinceId = $_POST['province'];
            
            $latitude = $_POST['latitude'];
            $longitude = $_POST['longitude'];
            
            $arrParams = array("place_id"=>$placeId,
                                "name"=>$name,
                                "address"=>$address,
                                "phone" => $phone, 
                                "mail" => $mail, 
                                "website" => $website, 
                                "product_service" => $productService, 
                                "description" => $description, 
                                "longitude" => $longitude, 
                                "latitude" => $latitude, 
                                "tag" => $tag, 
                                "small_picture" => $smallPicture, 
                                "province_id" => $provinceId, 
                                "map_icon" => $mapIcon,
                                "sale_user_id" => $userId,
                                "category_id" => $categoryId
                                );
            
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $merchantPlaceModel->edit($arrParams);
            $DB -> commit();
            echo $constants -> UPDATE_MERCHANT_SUCCESS;
        }catch(Exception $e){
            $DB -> rollback();
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function addMerchantPlaceAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $adminStreetModel = new Place_Model_AdminStreet();
            $allStreet = $adminStreetModel->getAllStreet();
            $this->view->allStreet = $allStreet;
            
            $adminPlaceCategoryModel = new Place_Model_AdminCategory();
            $allCategory = $adminPlaceCategoryModel->getAllCategory();
            $this->view->placeCategory = $allCategory;
            
            $adminProvinceModel = new Place_Model_AdminProvince();
            $allProvince = $adminProvinceModel->getAllProvince();
            $this->view->province = $allProvince;
            
            $tagCategory = array('Active life' => "Active life",
                                'ATM' => 'ATM',
                                'Beauty & Spa' => 'Beauty & Spa',
                                'Café' => 'Café',
                                'Education' => 'Education',
                                'Entertainment' => 'Entertainment',
                                'Finance' => 'Finance',
                                'Fuel station' => 'Fuel station',
                                'Health care' => 'Health care',
                                'Hotel & Accommodation' => 'Hotel & Accommodation',
                                'Nightlife' => 'Nightlife',
                                'Organizations' => 'Organizations',
                                'Restaurants' => 'Restaurants',
                                'Services' => 'Services',
                                'Shopping' => 'Shopping',
                                'Sightseeings' => 'Sightseeings',
                                'Street food & beverages' => 'Street food & beverages',
                                'Tourism & Travel' => 'Tourism & Travel',
                                'Transport' => 'Transport');
                                
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession->user;
            $userId = $user->sale_user_id;
            
            $userRoleModel = new Place_Model_SaleUserRole();
            $userRole = $userRoleModel->getRoleOfUser($userId);
            
            $saleUserRoleFeature = new Place_Model_SaleUserRoleFeature();
            $featureArr = $saleUserRoleFeature->getFeatureOfUserRole($userRole);
            $featureIdArr = array();
            foreach ($featureArr as $key => $value) {
                array_push($featureIdArr,$value->sale_feature_id);
            }
            if(!in_array($constants->FEATURE_CHECK_PLACE, $featureIdArr)){
                $this->_redirect('/place/index/index');
            }
            $this -> view -> userFeature = $featureArr;
            
            $this->view->tagCategory = $tagCategory;
            
            
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
        
    }
    
    public function getPlaceAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry = Zend_Registry::getInstance();
        $constants = $registry -> constants;
        try{
            if(!isset($_GET['place_id'])){
                throw new Exception($constants->ERROR_STRING);
            }
            $placeId = $_GET['place_id'];
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $placeDetail = $merchantPlaceModel->getPlaceDetail($placeId);
            
            $data = json_encode($placeDetail);
            echo $data;
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH . $constants -> LOG_FOLDER . 'production_' . date('Y_m_d') . $constants -> LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function loadPlaceAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $APPROVED = $constants->APPROVED;
            $page = 1;
            if(isset($_GET['page'])){
                $page = $_GET['page'];
            }
            $approve = $APPROVED;
            if(isset($_GET['approve'])){
                $approve = $_GET['approve'];
            }
            
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $placeList = $merchantPlaceModel->getPlaceByStatus($approve, $page);
            $this->view->result = $placeList;
            
            $merchantNumber = intval($merchantPlaceModel->getPlaceNumberByStatus($approve));
            $pageNumber = ceil($merchantNumber/($constants->PAGING_NUMBER));
            $this->view->pageNumber = $pageNumber;
            $this->view->merchantNumber = $merchantNumber;
            $this->view->page = $page;
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }


    public function loadPlaceNotApprovedAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $page = 1;
            if(isset($_GET['page'])){
                $page = $_GET['page'];
            }
            
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession->user;
            $userId = $user->sale_user_id;
            
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $placeNotApproved = $merchantPlaceModel->getPlaceNotApproved($userId ,$page);
            $placeNotApprovedNumber = $merchantPlaceModel->getPlaceNotApprovedNumber($userId);
            
            $pageNumber = ceil($placeNotApprovedNumber/($constants->PAGING_NUMBER));
            $this->view->pageNumber = $pageNumber;
            $this->view->merchantNumber = $placeNotApprovedNumber;
            $this->view->page = $page;
            
            $this->view->placeNotApproved = $placeNotApproved;
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    
    public function searchPlaceAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $APPROVED = $constants->APPROVED;
            $page = 1;
            if(isset($_GET['page'])){
                $page = $_GET['page'];
            }
            $approve = $APPROVED;
            if(isset($_GET['approve'])){
                $approve = $_GET['approve'];
            }
            
            $name = "";
            if(isset($_GET['merchant_name'])){
                $name = $_GET['merchant_name'];
            }
            
            $address = "";
            if(isset($_GET['address'])){
                $address = $_GET['address'];
            }
            
            $tel = "";
            if(isset($_GET['tel'])){
                $tel = $_GET['tel'];
            }
            
            $website = "";
            if(isset($_GET['website'])){
                $website = $_GET['website'];
            }
            
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $placeList = $merchantPlaceModel->searchMerchantPlace($name, $address,
                                                                    $tel, $website, 
                                                                    $approve, $page);
            $this->view->result = $placeList;
            
            $merchantNumber = intval($merchantPlaceModel->getSearchPlaceNumber($name, $address,
                                                                                $tel, $website,
                                                                                $approve ) );
            $pageNumber = ceil($merchantNumber/($constants->PAGING_NUMBER));
            $this->view->pageNumber = $pageNumber;
            $this->view->merchantNumber = $merchantNumber;
            $this->view->page = $page;
            
            $this->view->name = $name;
            $this->view->address = $address;
            $this->view->phone = $tel;
            $this->view->website = $website;
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }

    public function getTagAction() {
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry = Zend_Registry::getInstance();
        $constants = $registry -> constants;
        try{
            $out_charset = 'utf-8';
    
            $opts = array('http' => array('method' => "GET", 'header' => implode("\r\n", array('Content-type: text/plain; charset=' . $out_charset))));
            $context = stream_context_create($opts);
            
            $title = "";
            $name = $_GET['name'];
            if(isset($_GET['title'])){
                $title = $_GET['title'];    
            }
            $category = $_GET['category'];
            $titleConvert = "";
            if($title != null || strlen($title) > 0){
                $titleArr = explode("-",$title);
                $titleConvert = $titleArr[0];
            }
            $cate = $category;
            $urlGet = $constants -> URL_TAG_SERVICE . '?name=' . rawurlencode($name) 
                                    . '&cate=' . rawurlencode($cate) 
                                    . '&adr=&title=' . rawurlencode($titleConvert);
            $response = file_get_contents($urlGet, FALSE, $context);
            header('Content-type: text/html; charset=' . $out_charset);
    
            $tagObject = json_decode($response);
            $updatedObject = $tagObject->{'updated'};
            $productService = $updatedObject->{'productService'};
            $tagStr = $updatedObject->{'tags'};
            
            $output ="";
            if(strlen($productService) > 0){
                $output = $productService.', '.$tagStr.', '.$titleConvert; 
            }else{
                $output = $tagStr.$titleConvert;
            }
            
            echo $output;
        }catch(Exception $e){
            echo $registry -> constants -> ERROR_STRING;
            $writer = new Zend_Log_Writer_Stream(BASE_PATH . $constants -> LOG_FOLDER . 'production_' . date('Y_m_d') . $constants -> LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
        }
    }
    
    
}
